package com.dapengjiaoyu.polyv_video_plugin;


import android.app.Activity;
import android.util.Log;

import com.easefun.polyvsdk.PolyvSDKClient;
import com.easefun.polyvsdk.PolyvSDKUtil;
import com.easefun.polyvsdk.live.PolyvLiveSDKClient;
import com.easefun.polyvsdk.vo.PolyvVideoVO;

import org.json.JSONException;

import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** PolyvVideoPlugin */
public class PolyvVideoPlugin implements MethodCallHandler {

  static MethodChannel channel;

  private Activity activity;

  static private Registrar mRegistrar;

  /** Plugin registration. */
  public static void registerWith(final Registrar registrar) {
    mRegistrar = registrar;
    registrar.platformViewRegistry().registerViewFactory("plugins.polyv/video",new PolyvVideoViewFactory(registrar));
    registrar.platformViewRegistry().registerViewFactory("plugins.polyv/live",new PolyvLiveVideoViewFactory(registrar));

    channel = new MethodChannel(registrar.messenger(), "plugins.polyv/util");
    channel.setMethodCallHandler(new PolyvVideoPlugin());
  }

  @Override
  public void onMethodCall(final MethodCall call, final Result result) {
    switch (call.method){
      case "playerConfig":
        PolyvSDKClient client = PolyvSDKClient.getInstance();
        Map<String,String> arguments = (Map<String, String>) call.arguments;
        client.settingsWithConfigString(arguments.get("config"),arguments.get("aesKey"),arguments.get("iv"));
        client.initSetting(mRegistrar.context());

        PolyvLiveSDKClient.getInstance().initSetting(mRegistrar.context(), arguments.get("appId"),arguments.get("appSecret"));
        break;
      case "getFirstImage":
          Log.e("getFirstImage", (String) call.argument("vid"));
          new Thread(new Runnable() {
            @Override
            public void run() {
              try {
                final PolyvVideoVO video = PolyvSDKUtil.loadVideoJSON2Video((String) call.argument("vid"));
                mRegistrar.activity().runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    result.success(video.getFirstImage());
                  }
                });
              } catch (JSONException e) {
                e.printStackTrace();
              }
            }
          }).start();
        break;
      default:
        result.notImplemented();
    }
  }
}
